import { HTML5, WECHAT } from "cc/env";
import { Http, wechatEnv } from "../lib/Net";
import { Gamer } from "../lib/StorageInfo";
import { Util } from "../lib/Util";
import { sys } from "cc";
/**用户相关数据 */
type UserInfo = {
  signature: string
  rawData: string
  iv: string
  encryptedData: string
}
/**登录授权数据 */
type Login = {
  code: string
}
/**组合微给的数据 */
type User = UserInfo & Login;

/**回调配置 */
interface CallBreak {
  (res: { success: boolean }): void
};

/**微信授权字符枚举 */
enum Power {
  /**微信运动步数 */
  werun = "scope.werun",
  /**用户信息 */
  userInfo = "scope.userInfo",
  /**游戏圈加圈、点赞、发表数据 */
  gameClubData = "scope.gameClubData",
  /**地理位置 */
  userLocation = "scope.userLocation",
  /**保存到相册 */
  writePhotosAlbum = "scope.writePhotosAlbum",
  /**是否授权使用你的微信朋友信息 */
  WxFriendInteraction = "scope.WxFriendInteraction",
}

export class Wechat {
  //微信给的的数据
  option: User;
  /**用户授权表 */
  powers: any = null;
  constructor() {
    try {
      wx.getSetting({//获取授权对象设置到全局
        success: (powers: any) => {
          this.powers = powers;
        }
      });
    } catch (error) {
      console.log("不在微信平台无法使用wx对象api");
    }
  }
  /**分享游戏内 */
  shar(title: string = '中秋打麻将,登录领红包', imgurl: string = '', args: string = '') {
    wx.shareAppMessage({
      title: title,
      imageUrl: imgurl,
      query: new String('&').concat(args)
    });
  }
  exit(msg: string = '数据更新完成！请退出后重新打开') {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.exitMiniProgram();
          console.log('用户点击确定')
        }
      }
    })
  }
  getEnv() {
    let env: 'develop' | 'trial' | 'release' = 'trial';
    if (HTML5) {//如果是网页端就返回本地开发环境
      env = 'develop';
    }
    try {
      env = wx.getAccountInfoSync().miniProgram.envVersion;
    } catch (error) { }
    return env;
  }
  static isiOS(): boolean {
    //判断是否为iOS平台 
    if (WECHAT) {
      return !!String(wx.getSystemInfoSync().system).match(/iOS/g)
    } else {
      return sys.os === 'iOS';
    }
  }
  /**10个=1元 20个 = 2元 根据微信公众平台虚拟支付的后台配置给值
   * @param [count] 数量
  */
  pay(count = 0, orders: string) {
    console.log("当前微信支付环境为:", wechatEnv);
    wx.requestMidasPayment({
      env: wechatEnv,
      mode: "game",
      offerId: '1450088917',
      currencyType: "CNY",
      buyQuantity: count,//数量
      outTradeNo: orders,//订单号
      success: (suc: any) => {
        console.log("微信支付接口数据", suc);
        new Http((suc: { code: number, msg: string }) => {
          console.log('http成功数据!!!!', suc);
          new Util.Alert().ShowAlert({//弹窗提示
            cancel: false,
            confrm: true,
            msg: suc.msg,
            callfun: (arg, arg2) => {
              arg2.destroy();
            },
          })
        }).paysuc({
          outTradeNo: orders//订单号
        })
      },
      fail: (err: any) => {
        // console.log("支付错误");
        new Util.Alert().ShowAlert({//弹窗提示
          cancel: false,
          confrm: true,
          msg: '支付取消',
          callfun: (arg, arg2) => {
            arg2.destroy();
          },
        })
      }
    })
  }
  openMahjong() {//打开龙游麻将
    try {
      wx.navigateToMiniProgram({
        appId: 'wxea4fc0ffdc311768',
        path: '',
        extraData: {
          foo: 'release'
        },
        envVersion: 'release',
        success(res) {
          console.log("打开成功！");
        }
      })
    } catch (error) {
      console.log("不在微信平台无法使用wx对象api");
    }
  }
  /**快速登陆不弹窗授权 没授权不成功*/
  fastLogin(fun: CallBreak) {
    try {
      setTimeout(() => {
        console.log("微信授权对象", this);
        if (this.powers.authSetting[Power.userInfo]) {
          // @ts-ignore
          wx.getUserInfo({//拿取用户信息
            success: (res2: UserInfo) => {
              wx.login({
                success: (res: Login) => {
                  let option = { signature: res2.signature, rawData: res2.rawData, iv: res2.iv, encryptedData: res2.encryptedData, code: res.code };
                  this.getInfo(option, fun);
                },
              })
            }
          });
        } else {
          fun({ success: false });
        }
      }, 500);
    } catch (error) {
      console.log("不在微信平台无法使用wx对象api");
    }
  }
  /**登录弹窗授权 */
  Login(fun: CallBreak) {
    try {
      //@ts-ignore
      wx.getUserProfile({//显示授权弹框拿取用户信息
        desc: '用来登录',
        success: (res2: UserInfo) => {
          wx.login({
            success: (res: Login) => {
              console.log("微信返回的登录数据", res, res2);
              let option = { signature: res2.signature, rawData: res2.rawData, iv: res2.iv, encryptedData: res2.encryptedData, code: res.code };
              this.getInfo(option, fun);
            }
          })
        }
      })
    } catch (error) {
      console.log("不在微信平台无法使用wx对象api");
    }
  }
  private getInfo(option: User, callBrakfun: CallBreak) { //和自家的后端拿取数据
    new Http((suc: any) => {
      if (suc.code === 0) {
        new Gamer().saveData(suc);
        callBrakfun({ success: true });
        console.log("微信登陆成功数据:", suc);
      } else {
        // new Gamer().clear();
        callBrakfun({ success: false });
        console.info("微信登录失败数据:", suc, option);
      }
    }).loginwx(option);
  }
  Login2(callBrakfun: CallBreak) {
    wx.getSetting({       //查询授权信息
      success: res => {   //查询授权信息
        if (res.authSetting["scope.userInfo"]) { //如果已经授权用户信息[快速登录]
          wx.login({      //拿到code
            success: (res: Login) => {  //拿到code
              wx.getUserInfo({          //拿取用户信息
                success: (infoResp) => {
                  console.log(infoResp);
                  let option = {
                    signature: infoResp.signature,
                    rawData: infoResp.rawData,
                    iv: infoResp.iv,
                    encryptedData: infoResp.encryptedData,
                    code: res.code
                  };                    //组合好后台登录需要的数据对象
                  this.getInfo(option, callBrakfun);
                }
              });
            }
          });
        } else {
          //@ts-ignore
          wx.getUserProfile({   //显示授权弹框拿取用户信息
            desc: '用来登录',
            success: (res2: UserInfo) => {
              wx.login({
                success: (res: Login) => {
                  // console.log("微信返回的登录数据", res, res2);
                  let option = {
                    encryptedData: res2.encryptedData,
                    signature: res2.signature,
                    rawData: res2.rawData,
                    iv: res2.iv,
                    code: res.code
                  };
                  this.getInfo(option, callBrakfun);
                }
              });
            },
            fail: (res) => {
              console.log('用户拒绝授权', res);
            }
          });
        }
      }
    });
  }
}